package com.wlz.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * netty 编解码
 * @author wlz
 * @date 2022-07-09  2:09 下午
 */
@Slf4j
public class CodecNettyClient {


    public static void main(String[] args) {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // string 编码器
//                            socketChannel.pipeline().addLast("encoder", new StringEncoder());
                            // 对象编码器
//                            socketChannel.pipeline().addLast(new ObjectEncoder());
                            socketChannel.pipeline().addLast(new CodecNettyClientHandler());

                        }
                    });

            log.info(" netty client start .... ");

            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();

            cf.channel().closeFuture().sync();

        } catch (Exception e) {
            log.error("CodecNettyClient error : {}", e);
        }finally {
            group.shutdownGracefully();
        }


    }
}
